/**
 * 
 */
package com.mdxl.first.Dao.db;

import java.util.ArrayList;
import java.util.List;

import com.mdxl.first.util.DataTypeUtils;
import com.mdxl.first.util.KeegooConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;


/**
 * mongo写
 *
 */
public class MongoDBWriteConnection extends AbstarctMongoDBConnection{

	protected static Logger logger = LoggerFactory.getLogger(MongoDBReadConnection.class);
	/**
	 * Mongodb连接实例
	 * 
	 * @return
	 */
	public MongoClient getMongoClient() {
		if(super.instance==null){
			try {
				MongoClientOptions.Builder build = new MongoClientOptions.Builder();
//				build.autoConnectRetry(true);//是否连接自动重试
				build.connectionsPerHost(Integer.valueOf(KeegooConfig.mongodbWriteConnectionsCount));//连接数
				build.connectTimeout(5000);//连接超时时间
				build.maxWaitTime(10000);//最大等待时间
				build.socketKeepAlive(true);//保持连接
				build.socketTimeout(0);//0，不限时间
				//build.maxAutoConnectRetryTime(1);//最大重试时间，单位秒
				build.threadsAllowedToBlockForConnectionMultiplier(50);
				MongoClientOptions options = build.build();
				
				List<ServerAddress> addresses = new ArrayList<ServerAddress>();
				if (DataTypeUtils.isNotEmpty(KeegooConfig.mongoDBWriteHOSTS)) {
					String[] hosts = KeegooConfig.mongoDBWriteHOSTS.split(",");
					String[] ports = KeegooConfig.mongoDBWritePORTS.split(",");
					for (int i = 0; i < hosts.length; i++) {
						ServerAddress address = new ServerAddress(hosts[i], Integer.valueOf(ports[i]));
						addresses.add(address);
					}
					super.instance = new MongoClient(addresses, options);
					super.isShard = true;
				}else{
					ServerAddress addr = new ServerAddress(KeegooConfig.mongoDBWriteIP, Integer.valueOf(KeegooConfig.mongoDBWritePORT));
					super.instance = new MongoClient(addr, options);
					super.isShard = false;
				}
			} catch (NumberFormatException e) {
				logger.error("Mongon数据库服务器连接失败！", e);
			}
		}
		return super.instance;
	}

}
